package cn.tedu.csmall.product.service.impl;


import cn.tedu.csmall.commons.ex.ServiceException;
import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.CategoryAttributeTemplateMapper;
import cn.tedu.csmall.product.mapper.CategoryMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.*;
import cn.tedu.csmall.product.pojo.param.CategoryAddNewParam;
import cn.tedu.csmall.product.pojo.param.CategoryUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.CategoryListItemVO;
import cn.tedu.csmall.product.pojo.vo.CategoryStandardVo;
import cn.tedu.csmall.product.pojo.vo.CategoryTreeItemVO;
import cn.tedu.csmall.product.service.CategoryService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    BrandCategoryMapper brandCategoryMapper;
    @Autowired
    CategoryAttributeTemplateMapper categoryAttributeTemplateMapper;
    @Autowired
    SpuMapper spuMapper;

    @Override
    public void addNew(CategoryAddNewParam categoryAddNewParam) {
        log.debug("开始处理【添加分类】的业务,参数: {}", categoryAddNewParam);
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", categoryAddNewParam.getName());
        int countName = categoryMapper.selectCount(queryWrapper);
        log.debug("根据相册名称统计匹配的分类数量，结果：{}", categoryAddNewParam);
        if (countName > 0) {
            String message = "添加分类失败。分类名称已存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 通过参数对象获取parentId
        Long parentId = categoryAddNewParam.getParentId();
        // 预设depth（深度值）为1
        Integer depth = 1;
        CategoryStandardVo parentCategory = null;
        // 判断parentId是否不为0
        if (parentId != 0) {
            // 否：调用Mapper对象的getStandardById()查询父级类别
            parentCategory = categoryMapper.getStandardById(parentId);
            // 判断查询结果（父级类别）是否为null
            if (parentCategory == null) {
                // 是：抛出异常
                String message = "添加类别失败，父级类别不存在!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            } else {
                // 否：depth（深度值）为：父级类别的depth + 1
                depth = parentCategory.getDepth() + 1;
            }
        }

        // 创建Category对象
        Category category = new Category();
        // 复制属性
        BeanUtils.copyProperties(categoryAddNewParam, category);
        // 补全Category对象的属性值：depth >>>
        category.setDepth(depth);
        // 补全Category对象的属性值：isParent >>> 固定为0
        category.setIsParent(0);
        category.setGmtCreate(LocalDateTime.now());
        category.setGmtModified(LocalDateTime.now());
        log.debug("准备将新的分类数据写入到数据库，数据：{}", category);
        // 调用Mapper对象的insert()方法执行插入
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            String message = "添加分类失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的分类数据写入到数据库，完成！");

        //判断parentId是否为0,并判断父级类别的isParent是否为0
        if (parentId != 0 && parentCategory.getIsParent() == 0) {
            // 是：将父级类别的isParent更新为1
            Category updateParentCategory = new Category();
            updateParentCategory.setId(parentId);
            updateParentCategory.setIsParent(1);
            rows = categoryMapper.updateById(updateParentCategory);
            if (rows != 1) {
                String message = "添加分类失败，服务器忙，请稍后再试!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除分类】的业务,参数: {}", id);
        //检查分类是否存在，如果不存在，则抛出异常
        CategoryStandardVo currentCategory = categoryMapper.getStandardById(id);
        log.debug("根据分类ID统计匹配的品牌数量，结果：{}", currentCategory);
        if (currentCategory == null) {
            String message = "删除分类失败，分类数据不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的isParent是否为1，如果是，则抛出异常
        if (currentCategory.getIsParent() == 1) {
            String message = "删除分类失败，该类别包含子类别!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //检查是否有品牌类别关联到此品牌，如果存在，则抛出异常
        QueryWrapper<BrandCategory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("category_id", id);
        int countByCategoryId2 = brandCategoryMapper.selectCount(queryWrapper2);
        log.debug("根据分类ID统计匹配的品牌类别数量，结果：{}", countByCategoryId2);
        if (countByCategoryId2 > 0) {
            String message = "删除分类失败，仍有品牌类别关联到此分类";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //检查是否有分类属性模板关联到此分类，如果存在，则抛出异常
        QueryWrapper<CategoryAttributeTemplate> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("category_id", id);
        int countByCategoryId3 = categoryAttributeTemplateMapper.selectCount(queryWrapper3);
        log.debug("根据分类ID统计匹配的分类属性模板数量，结果：{}", countByCategoryId3);
        if (countByCategoryId3 > 0) {
            String message = "删除分类失败，仍有分类属性模板关联到此分类";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //检查是否有spu关联到此分类，如果存在，则抛出异常
        QueryWrapper<Spu> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("category_id", id);
        int countByCategoryId4 = spuMapper.selectCount(queryWrapper4);
        log.debug("根据分类ID统计匹配的spu数量，结果：{}", countByCategoryId4);
        if (countByCategoryId4 > 0) {
            String message = "删除分类失败，仍有spu关联到此分类";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除分类失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("删除分类成功!");

        // 调用Mapper对象的countByParentId方法，根据以上查询结果中的parentId，执行统计
        Long parentId = currentCategory.getParentId();
        int countByParentId = categoryMapper.countByParentId(parentId);
        // 判断统计结果为0，则将父级类别的isParent更新为0
        if (countByParentId == 0) {
            Category parentCategory = new Category();
            parentCategory.setId(parentId);
            parentCategory.setIsParent(0);
            rows = categoryMapper.updateById(parentCategory);
            if (rows != 1) {
                String message = "删除类别失败，服务器忙，请稍后再试!";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }

    }

    @Override
    public void updateCategory(Long categoryId, CategoryUpdateInfoParam categoryUpdateInfoParam) {
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            String message = "修改类别失败,根据类别id没有找到此类别";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        BeanUtils.copyProperties(categoryUpdateInfoParam, category);
        category.setGmtModified(LocalDateTime.now());
        int rows = categoryMapper.updateById(category);
        if (rows != 1) {
            String message = "修改分类失败，服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("修改类别成功!");
    }

    @Override
    public List<CategoryListItemVO> listByParentId(Long parentId) {
        return categoryMapper.listByParentId(parentId);
    }

    @Override
    public CategoryStandardVo getStandardById(Long id) {
        log.debug("开始处理【根据ID查询类别详情】的业务，参数：{}", id);
        CategoryStandardVo queryResult = categoryMapper.getStandardById(id);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "查询类别详情失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public void setEnable(Long id) {
        log.debug("开始处理【启用类别】的业务，参数：{}", id);
        updateEnableById(id,1);
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理【禁用类别】的业务，参数：{}", id);
        updateEnableById(id,0);
    }

    @Override
    public List<CategoryTreeItemVO> listTree() {
        log.debug("开始处理【获取类别树】的业务，参数:无");
        List<CategoryTreeItemVO> categoryTree = new ArrayList<>();

        List<CategoryListItemVO> categoryList = categoryMapper.list();
        Map<Long,CategoryListItemVO> allCategoryMap = transformListToMap(categoryList);
        for (Long key : allCategoryMap.keySet()) {
            CategoryListItemVO categoryListItemVO = allCategoryMap.get(key);
            if (categoryListItemVO.getParentId() == 0){
                CategoryTreeItemVO categoryTreeItemVO = convertListItemToTreeItem(categoryListItemVO);
                categoryTree.add(categoryTreeItemVO);

                fillChildren(categoryListItemVO,categoryTreeItemVO,allCategoryMap);
            }
        }
        return categoryTree;
    }

    private Map<Long,CategoryListItemVO> transformListToMap(List<CategoryListItemVO> categoryList){
        Map<Long,CategoryListItemVO> allCategoryMap = new LinkedHashMap<>();
        for (CategoryListItemVO listItemVO : categoryList) {
            if (listItemVO.getEnable() == 0){
                continue;
            }
            allCategoryMap.put(listItemVO.getId(),listItemVO);
        }
        return allCategoryMap;
    }

    private void fillChildren(CategoryListItemVO categoryListItemVO,CategoryTreeItemVO currentTreeItem,Map<Long,CategoryListItemVO> allCategoryMap){
        if (categoryListItemVO.getIsParent() == 1){
            currentTreeItem.setChildren(new ArrayList<>());
            for (Long key : allCategoryMap.keySet()) {
                CategoryListItemVO mapItem = allCategoryMap.get(key);
                if (mapItem.getParentId() == categoryListItemVO.getId()){
                    CategoryTreeItemVO categoryTreeItemVO = convertListItemToTreeItem(mapItem);
                    currentTreeItem.getChildren().add(categoryTreeItemVO);
                    if (mapItem.getIsParent() == 1){
                        fillChildren(mapItem,categoryTreeItemVO,allCategoryMap);
                    }
                }
            }
        }
    }

    private CategoryTreeItemVO convertListItemToTreeItem(CategoryListItemVO categoryListItemVO){
        return new CategoryTreeItemVO()
                .setValue(categoryListItemVO.getId())
                .setLabel(categoryListItemVO.getName());
    }


    private void updateEnableById(Long id,Integer enable){
        //调用Mapper对象的getStandardById()方法执行查询
        CategoryStandardVo currentCategory = categoryMapper.getStandardById(id);
        // 判断查询的结果是否为null 如果是，则抛出异常
        if (currentCategory == null){
            String message = ENABLE_TEXT[enable] + "类别失败,类别数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        // 判断查询结果中的enable与参数enable是否相同，如果是，则抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (currentCategory.getEnable() == enable) {
            String message = ENABLE_TEXT[enable] + "类别失败，此类别已经处于" + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建Category对象
        Category updateCategory = new Category();
        // 向Category对象中封装属性值：id, enable，均来自方法参数
        updateCategory.setId(id);
        updateCategory.setEnable(enable);
        // 调用Mapper对象的update()方法执行更新
        int rows = categoryMapper.updateById(updateCategory);
        if (rows != 1){
            String message = ENABLE_TEXT[enable] + "类别失败,服务器忙，请稍后再试!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }

}
